import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { CustomLogger } from 'src/services/custom-logger'

@Injectable()
export class AuthGuard implements CanActivate {
    private readonly logger = new CustomLogger(AuthGuard.name)
    constructor(private jwtService: JwtService) {}

    async canActivate(context: ExecutionContext): Promise<boolean> {
        const request = context.switchToHttp().getRequest()

        const token = this.extractTokenFromHeader(request)

        if (!token) {
            throw new UnauthorizedException()
        }

        let payload: { account: string } | null = null

        try {
            payload = await this.jwtService.verifyAsync<{ account: string }>(token)
        } catch (e) {
            this.logger.error('解析token遇到错误', e)
            throw new UnauthorizedException()
        }

        if (payload == null || payload.account == null) {
            this.logger.error('解析token遇到错误', payload)
            throw new UnauthorizedException()
        }

        return true
    }

    private extractTokenFromHeader(request: any): string | undefined {
        const [type, token] = request.headers.authorization?.split(' ') ?? []
        return type === 'Bearer' ? token : undefined
    }
}
